import IdentityManager from "@geoscene/core/identity/IdentityManager";
import ServerInfo from "@geoscene/core/identity/ServerInfo";
import { set } from "lodash";
import useMap2D from "./useMap2D";


export default function useMapAuth() {
    const { MapViewport2D } = useMap2D();

    useEffect(() => {
        silentSignIn();
    }, []);

    // 静默登录函数
    async function silentSignIn() {
        const { token } = window?.map || {};
        // 配置服务器信息
        const serverUrl = "https://cim.szssscri.com/portal"; // 门户地址
        const tokenServiceUrl = `https://cim.szssscri.com/portal/sharing/rest/generateToken`; // Token服务端点
        const serverInfo = new ServerInfo({
            server: serverUrl,
            tokenServiceUrl: tokenServiceUrl,
            hasPortal: true,
        });

        // 用户凭证
        const userInfo = {
            username: "ZJDSF2024", // 账号
            password: "PQZSsxH9"  // 密码
        };

        try {
            let success = false;
            if (token) {
                // 2. 注册令牌
                IdentityManager.registerToken({
                    server: 'https://cim.szssscri.com/portal/sharing/rest', // https://cim.szssscri.com/sharing/rest
                    token: token,
                    ssl: true,
                });
                const credential = await IdentityManager.getCredential("https://cim.szssscri.com/portal"); // https://cim.szssscri.com
                // console.log("凭证获取成功", credential);

                if (credential?.userId) {
                    success = true;
                }
            }

            if (!success) {
                // 1. 生成令牌
                const tokenResponse = await IdentityManager.generateToken(serverInfo, userInfo);
                // 2. 注册令牌
                IdentityManager.registerToken({
                    server: 'https://cim.szssscri.com/portal/sharing/rest', // https://cim.szssscri.com/sharing/rest
                    token: tokenResponse.token,
                    ssl: true,
                    expires: tokenResponse.expires
                });
                const mapObj = window?.map || {};
                set(mapObj, 'token', tokenResponse.token);
                set(window, 'map', mapObj);
            }
        } catch (error) {
            console.error("静默登录失败:", error);
        }
    }

    return {
        MapViewport2D
    }
}
